package middleware.optimize;

import middleware.llvm.instruction.AllocaInstruction;

import java.util.*;

/**
 * 冲突图，用于寄存器分配
 *
 * @author 杨凯伟
 * @date 2024/10/30
 */
public class ConflictDiagram {
    private final Map<AllocaInstruction, Set<AllocaInstruction>> conflictVar = new HashMap<>();

    public ConflictDiagram(List<AllocaInstruction> elements) {
        elements.forEach(elm -> conflictVar.put(elm, new HashSet<>()));
    }

    public void addConflict(AllocaInstruction a, AllocaInstruction b) {
        conflictVar.get(a).add(b);
        conflictVar.get(b).add(a);
    }

    public void removeNode(AllocaInstruction node) {
        conflictVar.remove(node);
        conflictVar.keySet().forEach(otherNode -> conflictVar.get(otherNode).remove(node));
    }

    public ConflictDiagram copy() {
        var newDiagram = new ConflictDiagram(this.conflictVar.keySet().stream().toList());
        this.conflictVar.forEach((node, conflictSet) -> newDiagram.conflictVar.put(node, new HashSet<>(conflictSet)));
        return newDiagram;
    }

    public boolean isEmpty() {
        return conflictVar.isEmpty();
    }

    public Set<AllocaInstruction> getConflict(AllocaInstruction a) {
        return conflictVar.get(a);
    }

    public Set<AllocaInstruction> getNodes() {
        return conflictVar.keySet();
    }
}
